package com.yl.chainStore.control.pay

import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.entity.pay.PayCompanyCouponsModel
import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.payrule.coupons.CouponsRuleTypeEnum
import com.yl.chainStore.payrule.common.RuleField
import com.yl.chainStore.pojo.vo.pay.CouponsToCustomerVo
import com.yl.chainStore.pojo.vo.pay.CouponsTypeOptionSelectVo
import com.yl.chainStore.pojo.vo.pay.PayCompanyCouponsModelSelectVo
import com.yl.chainStore.pojo.vo.pay.PayCustomerCouponsSelectVo
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*
import java.lang.Exception
import java.util.*

/**
 * 优惠卷
 */
@RestController
@RequestMapping("pay/coupons")
open class PayCustomerCouponsController(

	private val iCustomerInfoService: ICustomerInfoService,
	private val iWebCompanyDeptService: IWebCompanyDeptService,

	) : BaseCtrl() {

	/**
	 * 创建一个优惠卷模板
	 */
	@PostMapping("createCustomerCouponsModel")
	@PermsCode("pay:coupons:createCustomerCouponsModel")
	@Transactional(rollbackFor = [Exception::class])
	open fun createCustomerModel(@RequestBody model: PayCompanyCouponsModel): ResponseBody {
		val createCustomerCouponsModel = iWebCompanyDeptService.createCustomerCouponsModel(model)
		if (createCustomerCouponsModel.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return createCustomerCouponsModel
		}
		return returnSuccess()
	}

	/**
	 * 获取可发放优惠劵列表
	 */
	@GetMapping("getIssueCouponsModel")
	@PermsCode("pay:coupons:getIssueCouponsModel")
	@Transactional
	open fun getIssueCouponsModel(): ResponseBody {
		val customerCouponsModelList = iWebCompanyDeptService.getCustomerCouponsModelList(
			PayCompanyCouponsModelSelectVo(
				status = 1,
				companyId = getContext().companyId,
				useNow = true
			)
		)
		return returnSuccess(customerCouponsModelList)
	}

	/**
	 * 给客户发放优惠卷
	 */
	@PostMapping("addCouponsToCustomer")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("customer:order:coupon:issue")
	open fun addCouponsToCustomer(@RequestBody vo: CouponsToCustomerVo): ResponseBody {
		val addCouponsToCustomer = iCustomerInfoService.addCouponsToCustomer(vo.modelId, vo.customerId, vo.count)
		if (addCouponsToCustomer.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return addCouponsToCustomer
	}

	/**
	 * 获取客户优惠卷分页
	 */
	@PostMapping("getCustomerCouponsModelPage")
	@Transactional
	open fun getCustomerCouponsModelPage(): ResponseBody {
		// TODO: 2021/8/16 暂不需要
		return returnSuccess()
	}

	/**
	 * 客户优惠卷列表（当前能用所有）
	 */
	@PostMapping("getCustomerCanUseCoupons")
	@Transactional
	open fun getCustomerCanUseCoupons(@RequestBody vo: PayCustomerCouponsSelectVo): ResponseBody {
		if (vo.customerId == null) {
			return returnError(ErrorCode.PARAM_EMPTY)
		}
		vo.companyId = getContext().companyId
		vo.subCompanyId = getContext().subCompanyId
		vo.nowTime = Date()
		vo.flag = Status.NEW_ADD
		val resList = mutableListOf<Map<String, Any>>()
		val customerCouponsList = iCustomerInfoService.getCustomerCouponsList(vo)
		for (coupons in customerCouponsList) {
			val map = mutableMapOf<String, Any>()
			map["id"] = coupons.id
			map["name"] = coupons.title
			map["endTime"] = coupons.endTime
			resList.add(map)
		}
		return returnSuccess(resList)
	}

	/**
	 * 客户优惠卷列表 当前订单能用
	 */
	@PostMapping("getCustomerCanUseCouponsByOrder")
	@Transactional
	open fun getCustomerCanUseCouponsByOrder(@RequestBody order: PayCustomerOrder): ResponseBody {
		val vo =  PayCustomerCouponsSelectVo()
		vo.customerId = order.customerId
		vo.companyId = getContext().companyId
		vo.subCompanyId = getContext().subCompanyId
		vo.nowTime = Date()
		vo.flag = Status.NEW_ADD
		val resList = mutableListOf<Map<String, Any>>()
		val customerCouponsList = iCustomerInfoService.getCustomerCouponsList(vo)
		for (coupons in customerCouponsList) {
			if(!coupons.getOtherContentObj().canUseForOrder(order)){
				continue
			}
			val map = mutableMapOf<String, Any>()
			map["id"] = coupons.id
			map["name"] = coupons.title
			map["endTime"] = coupons.endTime
			resList.add(map)
		}
		return returnSuccess(resList)
	}

	/**
	 * 获取优惠卷规则种类
	 */
	@GetMapping("getCouponsTypeSelect")
	@Transactional
	open fun getCouponsTypeSelect(): ResponseBody {
		val list = mutableListOf<Map<String, Any>>()
		for (item in CouponsRuleTypeEnum.values()) {
			if (item == CouponsRuleTypeEnum.DEFAULT) {
				continue
			}
			val map = mutableMapOf<String, Any>()
			map["id"] = item.typeName
			map["name"] = item.typeName
			list.add(map)
		}
		return returnSuccess(list)
	}

	/**
	 * 获取优惠卷规则种类配置
	 */
	@PostMapping("getCouponsTypeOption")
	@Transactional
	open fun getCouponsTypeOption(@RequestBody vo: CouponsTypeOptionSelectVo): ResponseBody {
		val list = mutableListOf<Map<String, Any>>()
		val enum = vo.ruleType
		val fs = enum.clazz.declaredFields
		try {
			for (f in fs) {
				val showField: RuleField = f.getAnnotation(RuleField::class.java) ?: continue
				val map = mutableMapOf<String, Any>()
				map["name"] = f.name
				map["viewName"] = showField.viewName
				map["dataSource"] = showField.dataSource
				map["must"] = showField.must
				map["type"] = showField.type
				map["value"] = showField.value
				list.add(map)
			}
		} catch (e: Exception) {
			e.printStackTrace()
		}
		return returnSuccess(list)
	}

	/**
	 * 获取优惠卷类型（基础3大类）
	 */
	@GetMapping("getCouponsTypeList")
	open fun getCouponsTypeList():ResponseBody{
		val resList = mutableListOf<Map<String,Any>>()
		resList.add(TypeEnum.CUSTOMER_COUPONS_CASH.getMap())
		resList.add(TypeEnum.CUSTOMER_COUPONS_PACKAGE.getMap())
		resList.add(TypeEnum.CUSTOMER_COUPONS_DISCOUNT.getMap())
		return returnSuccess(resList)
	}

	/**
	 * 获取优惠卷时间计算方式类型
	 */
	@GetMapping("getCouponsTimeTypeList")
	@Transactional
	open fun getCouponsTimeTypeList():ResponseBody{
		val resList = mutableListOf<Map<String,Any>>()
		resList.add(TypeEnum.CUSTOMER_COUPONS_TIME_TYPE_DAY_TO_DAY.getMap())
		resList.add(TypeEnum.CUSTOMER_COUPONS_TIME_TYPE_AFTER_DAY_TO_DAY.getMap())
		return returnSuccess(resList)
	}


}

